#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

//#define READ_FILE

struct Mat
{
	int m, n;
	bool operator==(Mat& mat)
	{
		return m == mat.m && n == mat.n;
	}
};
Mat g_mat[26];

int calc(const string& str)
{
	vector<Mat> stack;
	
	Mat parenthes;
	parenthes.m = -1;
	parenthes.n = -1;
	
	int res = 0;
	
	for (unsigned int i = 0; i < str.length(); ++i)
	{
		if (str[i] == '(')
		{
			stack.push_back(parenthes);
			continue;
		}
		
		Mat mat;
		if (str[i] == ')')
		{
			mat = *(stack.end()-1);
			stack.pop_back();
			stack.pop_back(); // left parenthes
		}
		else
		{
			mat = g_mat[str[i]-'A'];
		}
		
		// put mat into stack
		if (stack.size() == 0)
		{
			stack.push_back(mat);
		}
		else if (*(stack.end()-1) == parenthes)
		{
			stack.push_back(mat);
		}
		else
		{
			Mat& matPre = *(stack.end()-1);
			if (matPre.n != mat.m)
			{
				return -1;
			}
			res += (matPre.m * matPre.n * mat.n);
			matPre.n = mat.n;
		}
	}
	
	return res;
}

int main()
{
#ifdef READ_FILE
	ifstream in("1094.input");
	if (!in) { in.open("../1094.input"); }
#else
	#define in cin
#endif

	int n;
	in >> n;
	while (n--)
	{
		char ch;
		in >> ch;
		in >> g_mat[ch-'A'].m >> g_mat[ch-'A'].n;
	}
	
	string str;
	while (in >> str)
	{
		int result = calc(str);
		if (result == -1)
		{
			cout << "error" << endl;
		}
		else
		{
			cout << result << endl;
		}
	}
	return 0;
}